package ext.tianma.bom.service.partQuantity;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import wt.fc.PersistenceHelper;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfProcess;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.EnumerationUtil;
import ext.tianma.model.APLQuantity;
import ext.tianma.number.util.PartUtil;
import ext.tianma.part.AVLMaterial.AVLUtil;
import ext.tianma.part.AVLMaterial.constants.RangeChangeConstants;
import ext.tianma.project2.util.ProjectUtil;
import ext.tianma.util.TMUtil;

@Controller
@RequestMapping({ "/QuantityController" })
public class QuantityController {
	@Autowired
	QuantityService quantityservice;

	private static final Logger logger = LoggerFactory.getLogger(QuantityController.class);
	
	/**
	 * ERP传输成品数量接口入口
	 * @param param
	 * @param response
	 * @throws JSONException
	 * @author xucr
	 * @CreateDate 2020年10月12日
	 */
	@RequestMapping(value = "/calcQuantity", method = {RequestMethod.POST, RequestMethod.GET })
	public void calcQuantity(
			@RequestBody(required = false) String params,
			HttpServletResponse response) throws JSONException {
		logger.info("----ERP传输参数：" + params);
		response.setContentType("text/html;charset=UTF-8");
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			PrintWriter out = response.getWriter();
			JSONObject result = quantityservice.initERPData(params);
			out.print(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 查询APL用量
	 * @param params
	 * @param response
	 * @throws JSONException
	 * @author xucr
	 * @CreateDate 2020年11月6日
	 */
	@RequestMapping(value = "/queryQuantity", method = {RequestMethod.POST, RequestMethod.GET })
	public void queryQuantity(
			@RequestParam(value = "params", required = false) String params,
			HttpServletResponse response) throws JSONException {
		logger.info("----ERP传输参数：" + params);
		response.setContentType("text/html;charset=UTF-8");
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject(params);
			JSONObject result = quantityservice.showAPLQuantity(obj);
			out.print(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 查询配置中的使用范围(用于下拉列表使用)
	 * @param params
	 * @param response
	 * @throws JSONException
	 * @author xucr
	 * @CreateDate 2020年11月6日
	 */
	@RequestMapping(value = "/findQuantity", method = {RequestMethod.POST, RequestMethod.GET })
	public void findQuantity(HttpServletResponse response) throws JSONException {
		response.setContentType("text/html;charset=UTF-8");
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			PrintWriter out = response.getWriter();
			JSONObject result = quantityservice.getRangeValue();
			out.print(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	   * 查询配置中的使用范围(用于根据key取value)
	   * 
	   * @param params
	   * @param response
	   * @throws JSONException
	   * @author xucr
	   * @CreateDate 2020年11月6日
	   */
	@RequestMapping(value = "/findQuantity2", method = { RequestMethod.POST, RequestMethod.GET })
	public void findQuantity2(@RequestParam(value = "range", required = false) String range,
			@RequestParam(value = "wid", required = false) String wid, 
			HttpServletResponse response) throws JSONException {
		response.setContentType("text/html;charset=UTF-8");
	    boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
	    try {
	    	PrintWriter out = response.getWriter();
	    	Map<String, String> maps = QuantityConfig.getUsableRange();// 取配置中的
//	    	maps = AVLUtil.getIBARangeValue(); //八大属性，取对象中已定义的八大属性
	    	String rangeValue = TMUtil.conversion(maps.get(range));

	    	WfProcess wfprocess = (WfProcess) TMUtil.oid2Obj(wid);
	    	if (null != wfprocess) {
	    		WTPartMaster master = (WTPartMaster)wfprocess.getContext().getValue(RangeChangeConstants.PARTMASTER);
		        WTPart part = (WTPart) PartUtil.getWTPartByNumber(master.getNumber());
		        Map<String, String> map = EnumerationUtil.getEnumerationValues("Level"); // 等级枚举
		        APLQuantity aplQuantity = AVLUtil.getAPLQuantity(master.getPersistInfo().getObjectIdentifier().getId(), range);
		        String quantity = "0"; //无用量表的情况下，默认显示0
		        if(null != aplQuantity) {
		        	quantity = aplQuantity.getQuantity();
		        }
	
		        String level_enum_key = (String) IBAUtil.getIBAValue(part, range);
		        String level_enum_value = map.get(level_enum_key);
		        JSONObject object = new JSONObject();
		        // 使用范围
		        object.put("rangeKey", range);
		        object.put("rangeValue", rangeValue);
	
		        // 历史等级
		        object.put("levelKey", level_enum_key);
		        object.put("levelValue", level_enum_value);
		        
		        // 历史用量
		        object.put("num", quantity);
	
		        out.print(object.toString());
	    	}
	    } catch (IOException e) {
	      e.printStackTrace();
	    } catch (WTException e) {
	      e.printStackTrace();
	    } finally {
	      SessionServerHelper.manager.setAccessEnforced(enforce);
	    }
	}
	
	 /**
	   * 查询配置中的等级(用于根据key取value)
	   * 
	   * @param params
	   * @param response
	   * @throws JSONException
	   * @author xucr
	   * @CreateDate 2020年11月6日
	   */
	  @RequestMapping(value = "/findLevel", method = { RequestMethod.POST, RequestMethod.GET })
	  public void findLevel(@RequestParam(value = "level", required = false) String level, HttpServletResponse response)
	      throws JSONException {
	    response.setContentType("text/html;charset=UTF-8");
	    boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
	    try {
	      PrintWriter out = response.getWriter();

	      Map<String, String> maps = EnumerationUtil.getEnumerationValues("Level"); // 等级枚举
	      String levelValue = TMUtil.conversion(maps.get(level));

	      out.print(levelValue);
	    } catch (IOException e) {
	      e.printStackTrace();
	    } finally {
	      SessionServerHelper.manager.setAccessEnforced(enforce);
	    }
	  }
	  
	  /**
	   * 接受数据，保存到changeData
	   * @param params
	   * @param wid
	   * @param response
	   * @throws Exception
	   */
	  @RequestMapping(value = "/saveData", method = { RequestMethod.POST, RequestMethod.GET })
	  public void saveData(@RequestParam(value = "params", required = false) String params,
	      @RequestParam(value = "wid", required = false) String wid, 
	      HttpServletResponse response) throws Exception {
	    response.setContentType("text/html;charset=UTF-8");
	    boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
	    try {
	    	// 得到流程对象
	    	WfProcess wfProcess = (WfProcess) TMUtil.oid2Obj(wid);
	    	// 设置流程变量changeData
	    	ProcessData processdata = wfProcess.getContext();
	    	if (StringUtils.isNotEmpty(params)) {
	    		processdata.setValue(RangeChangeConstants.CHANGEDATA, params);
	    		wfProcess = (WfProcess) PersistenceHelper.manager.save(wfProcess);
	    	}
	    } finally {
	    	SessionServerHelper.manager.setAccessEnforced(enforce);
	    }
	 }
	
	/**
	 * 查询用户
	 * @param userName
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年11月17日
	 */
	@RequestMapping(value = "/getUserByName", method = { RequestMethod.POST, RequestMethod.GET })
	public void getUserByName(
			@RequestParam(value = "userName", required = false) String userName,
			HttpServletResponse response) throws Exception {
		
		response.setContentType("text/html;charset=UTF-8");
		TMUtil.setHeader(response);
		PrintWriter out = response.getWriter();
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			JSONArray array = new JSONArray();
			if(StringUtils.isNotEmpty(userName)) {
				List<WTUser> v =  ProjectUtil.getUserList("*" + userName + "*");
				
				if(null != v && v.size() > 0) {
					JSONObject obj = null;
					for(int i = 0 ; i < v.size(); i++) {
						obj = new JSONObject();
						WTUser u = (WTUser) v.get(i);
						obj.put("userName", u.getName());
						obj.put("userFullName", u.getFullName());
						array.put(obj);
					}
				}
			}
			JSONObject rsult = ProjectUtil.respInfo(array, array.length());
			out.print(rsult.toString());
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 导出报表
	 * @param params
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年11月17日
	 */
	@RequestMapping(value = "/export", method = { RequestMethod.POST, RequestMethod.GET })
	public void export(
			@RequestParam(value = "params", required = false) String params,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject(params);
			String path = quantityservice.exportToExcel(obj);
			
			JSONObject ob = new JSONObject();
			ob.put("path", path);
			ob.put("status", "success");
        	ob.put("message", "查询成功!");
        	
			out.print(ob.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 审批过程中，查看变更信息
	 * @param params
	 * @param response
	 * @throws Exception
	 * @author xucr
	 * @CreateDate 2020年11月18日
	 */
	@RequestMapping(value = "/viewQuantity", method = { RequestMethod.POST, RequestMethod.GET })
	public void viewQuantity(
			@RequestParam(value = "wid", required = false) String wid,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			PrintWriter out = response.getWriter();
			WfProcess w = (WfProcess) TMUtil.oid2Obj(wid);
			String changeData = (String) w.getContext().getValue(RangeChangeConstants.CHANGEDATA);
			
			out.print(changeData);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	   * 得到流程类型
	   * 
	   * @param params
	   * @param response
	   * @throws Exception
	   */
	@RequestMapping(value = "/processType", method = { RequestMethod.POST, RequestMethod.GET })
	public void processType(@RequestParam(value = "params", required = false) String params,
	      HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
	    boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
	    try {
	    	PrintWriter out = response.getWriter();
	    	WfProcess w = (WfProcess) TMUtil.oid2Obj(params);
	    	String type = (String) w.getContext().getValue(RangeChangeConstants.PROCESSTYPE_NAME);
	    	out.print(type);
	    } catch (IOException e) {
	      e.printStackTrace();
	    } finally {
	      SessionServerHelper.manager.setAccessEnforced(enforce);
	    }
	}
}
